const baseUrl = `${window.location.origin}/`;
layui.config({
    base: "./js/lib/layui-formSelects/src/"
}).extend({
    formSelects: 'formSelects-v4'
});
var options = {typeNumber:4,errorCorrectLevel:'M',size:200};
layui.use(['jquery','upload','element','table','layer','form','laydate','util', 'formSelects'], function(){
    var formSelects = layui.formSelects;
    var table = layui.table,
        layer = layui.layer;
    var upload = layui.upload;
    var laydate = layui.laydate;
    var form=layui.form;
    var util = layui.util;
    var nowTime = new Date().valueOf();
    $ = layui.jquery;

    laydate.render({
        elem: '#inspectDate',
        type: 'date',
        min: nowTime,
        range: true
        ,trigger:'click'//解决一闪而过的问题
    });


    laydate.render({
        elem: '#inspectStartTime',
        type: 'time'
    });

    laydate.render({
        elem: '#startDate',
        type: 'date'
    });
    laydate.render({
        elem: '#endDate',
        type: 'date'
    });

    //获取两日期之间日期列表函数
    function getdiffdate(stime,etime){
        //初始化日期列表，数组
        var diffdate = [];
        var i=0;
        //开始日期小于等于结束日期,并循环
        while(stime<=etime){
            diffdate[i] = stime;
            //获取开始日期时间戳
            var stime_ts = new Date(stime).getTime();
            //console.log('当前日期：'+stime   +'当前时间戳：'+stime_ts);
            //增加一天时间戳后的日期
            var next_date = stime_ts + (24*60*60*1000);

            //拼接年月日，这里的月份会返回（0-11），所以要+1
            var next_dates_y = new Date(next_date).getFullYear()+'-';
            var next_dates_m = (new Date(next_date).getMonth()+1 < 10)?'0'+(new Date(next_date).getMonth()+1)+'-':(new Date(next_date).getMonth()+1)+'-';
            var next_dates_d = (new Date(next_date).getDate() < 10)?'0'+new Date(next_date).getDate():new Date(next_date).getDate();

            stime = next_dates_y+next_dates_m+next_dates_d;
            //增加数组key
            i++;
        }
        return diffdate;
    }

    // 初始化线路列表
    loadLineList();
    // 初始化人员列表
    initStaffList();
    table.render({
        elem: '#insTasksTable'
        ,url: baseUrl+'/insTask/listByCondition'
        ,method: 'post'
        ,title: '巡检任务列表'
        ,cols: [[
            {type:'numbers',title: '序号'},
            {type:'checkbox'},
            {field: 'ID', title: '任务id',hide:true},
            {field: 'LINE_ID', title: '线路id',hide:true},
            {field: 'STAFF_ID', title: '线路id',hide:true},
            {field:'STAFF', title:'巡更人员',align : 'center' },
            {field:'LINE_NAME', title:'巡更线路',align : 'center' }
            ,{field:'INSPECT_DATE', title:'巡更日期',align : 'center', sort: true,templet:function(d){
                    return formatTime2(d.INSPECT_DATE);
                } }
            ,{field:'INSPECT_START_TIME', title:'巡更开始时间', align : 'center' }
            ,{field:'LINE_INSPECT_TIME', title:'巡更时长(min)', align : 'center' }
            ,{field:'LINE_INSPECT_ERROR_TIME', title:'误差时长(min)', align : 'center' }
            ,{field:'FINISH_TIME', title:'任务完成时间',align : 'center' ,templet:function(d){
                    return formatTime(d.FINISH_TIME);
                } }
            ,{field:'STATUS',align : 'center', title:'任务状态',templet:function(d){
                    return auditState(d.STATUS);
                }}
            ,{fixed: 'right', title:'操作', align : 'center',toolbar: '#barCmdOperate', width:220}
        ]]
        ,page: true
    });
    var listData;//
    function previewTaskList(data){
        table.render({
            elem: '#taskList'
            ,method: 'post'
            , limit: Number.MAX_VALUE // 数据表格默认全部显示
            ,title: '任务预览表'
            // ,page: true
            ,cols: [[
               {type:'numbers',title:'序号'},
                {field:'lineId', title:'巡更线路Id',align : 'center',hide:true },
                {field:'staffId', title:'巡更人员Id',align : 'center',hide:true },
                {field:'staff', title:'巡更人员',align : 'center' },
                {field:'lineName', title:'巡更线路',align : 'center' }
                ,{field:'inspectDate', title:'巡更日期',align : 'center' }
                ,{field:'inspectStartTime', title:'巡更开始时间', align : 'center'
                    , event: 'time', data_field: "inspectStartTime" }
                ,{field:'lineInspectTime', title:'巡更时长(min)', align : 'center' }
                ,{field:'lineInspectErrTime', title:'误差时长(min)', align : 'center' }
                ,{field:'earliestFinishTime', title:'任务最早完成时间', align : 'center' }
                ,{field:'latestFinishTime', title:'任务最晚完成时间', align : 'center' }
                ,{fixed: 'right', title:'操作', align : 'center',templet:function(data){
                        return '<div><a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a></div>';
                }}
            ]],
            data:data
            ,done:function (res,curr,count) {
                listData = res;
            }
        });
    }
    //监听单元格事件
    table.on('tool(taskList)', function (obj) {
        var data = obj.data;
        var newdata = {};
        if (obj.event === 'time') {
            var field = $(this).data('field');
            laydate.render({
                elem: this.firstChild
                , show: true //直接显示
                , closeStop: this
                ,type: 'time'
                ,trigger:'click'//解决一闪而过的问题
                , done: function (value, date) {
                    var inspectDate = obj.data.inspectDate;// 巡检日期
                    var insTime = obj.data.lineInspectTime;// 巡检时长
                    var insErrTime = obj.data.lineInspectErrTime;//误差时长
                    var earlyTime = addHours(new Date(inspectDate+' '+value), parseInt((Number(insTime)-Number(insErrTime))));
                    var latestTime = addHours(new Date(inspectDate+' '+value), parseInt((Number(insTime)+Number(insErrTime))));
                    newdata[field] = value;
                    newdata['earliestFinishTime'] = earlyTime;
                    newdata['latestFinishTime'] = latestTime;
                    obj.update(newdata);
                }
            });
        }else if(obj.event === 'del'){
            obj.del();
        }
    });
    function formatTime2(time){
        if(time){
            return util.toDateString(time, "yyyy-MM-dd");
        }
        return "";
    }
    function formatTime(time){
        if(time){
            return util.toDateString(time, "yyyy-MM-dd HH:mm:ss");
        }
        return "";
    }
    var staffList;
    function initStaffList() {
        var url = baseUrl+'/insTask/getStaffList?type='+encodeURI('staff');
        formSelects.config('select_staff_id', {
            beforeSuccess: function (id, url, searchVal, result) {
                // staffList = [{"id":"1","name":"张麻子"}, {"id":"2","name":"小鬼子"}, {"id":"3","name":"二狗子"}];
                staffList = result.data;
                var arr = [];
                var opt_html = "";
                $.each(staffList, function (index, item) {
                    arr[index] = {"name": item.name, "value": item.id,"selected":false};
                    opt_html += "<option value='" + item.id + "'>" + item.name + "</option>";
                });
                // 查看任务中人员是单选
                $("#mulStaff2").empty().append(opt_html);
                form.render('select');
                //然后返回数据
                return arr;
            }
        }).data('select_staff_id', 'server', {
            url: url
        });

    }
    // 搜索
    form.on('submit(search)',function(data){
        active['reload'].call(this);
        return false;
    });
    var active = {
        reload:function () {
            var staff = $("#staff").val();
            var line = $("#line_name").val();
            var startTime = $("#startDate").val();
            var endTime = $("#startDate").val();
            //执行重载
            table.reload('insTasksTable', {
                where: {staff:staff,line:line,startTime:startTime,endTime:endTime}
            }, 'data');
        }
    };
    // 新建任务
    $('#addTask').on('click',function () {
        //初始化
        $("#taskId").val("");
        $("#lineName").val("");
        $("#mulStaff").val("");
        $("#inspectDate").val("");
        $("#inspectStartTime").val("");
        form.render();
        layer.open({
            type: 1,
            title:"创建任务",
            offset: 'auto',
            skin:'demo-class',
            closeBtn: 1,
            shift: 2,
            area: ['100%', '100%'],
            shadeClose: true,
            content: $("#add_task_main")
        });
    });
    // 预览每日任务
    var taskArray = [];
    $('#reviewTask').on('click',function () {
        var lineId = $("#lineName").val();
        var lineName = $("#lineName option:selected").text().trim();
        var staffNames = formSelects.value('select_staff_id', 'all');
        var rangeDate = $("#inspectDate").val();
        var insStartTime = $("#inspectStartTime").val();
        if(lineId == null || staffNames.length === 0 || rangeDate === '' || insStartTime === ''){
            layer.msg("请选择相关信息", {icon: 5});
            return;
        }
        var insTime, insErrTime;
        for(var i in dictTypeArray){
            if(dictTypeArray[i].key === lineId){
                insTime = dictTypeArray[i].inspectTime;
                insErrTime = dictTypeArray[i].inspectErrorTime
            }
        }
        var data = [];
        // 日期截取
        var dateRange = rangeDate.split(" - ");
        var dateArr = getdiffdate(dateRange[0], dateRange[1]);
        for(var index in staffNames){
            for(var i in dateArr){
                var earlyTime = addHours(new Date(dateArr[i]+' '+insStartTime), parseInt((Number(insTime)-Number(insErrTime))));
                var latestTime = addHours(new Date(dateArr[i]+' '+insStartTime), parseInt((Number(insTime)+Number(insErrTime))));
                var task = {"staffId":staffNames[index].value,"staff":staffNames[index].name,
                    "lineId":lineId, "lineName":lineName,"inspectDate":dateArr[i],
                    "inspectStartTime":insStartTime, "lineInspectTime":insTime,
                    "lineInspectErrTime":insErrTime,"earliestFinishTime":earlyTime,
                    "latestFinishTime":latestTime
                };
                data.push(task);
            }
        }
        previewTaskList(data);
        taskArray = data;
    });

    function addHours(date, value) {
        date.setMinutes(date.getMinutes() + value);
        return formatTime(date);
    }
    //头工具栏事件
    table.on('tool(insTasksTable)', function(obj){
        switch(obj.event){
            case 'cancelTask':
                cancelTask(obj.data.ID);
                break;
            case 'recordDetail':
                showRecordsDetail(obj.data);
                break;
            case 'recordDelete':
                deleteRecord(obj.data.ID);
                break;
        }
    });
    function cancelTask(id){
        layer.confirm('确定要取消该任务么?',function(){
            $.ajax({
                url: baseUrl+"/insTask/modifyTask",
                type: "post",
                data: {"id": id},
                success: function (data) {
                    if(data.code === 200 ){
                        layer.msg('操作成功', {icon: 1});
                        setTimeout(function () {
                            active['reload'].call(this);
                        },1000);
                    }else{
                        layer.msg('操作失败', {icon: 5});
                    }
                }
            });

        });
    }

    $("#cancelBtn").on('click',function () {
        layer.closeAll();
        taskArray = [];
        previewTaskList(taskArray);
        return false;
    });
    $("#confrim").on('click',function () {
        layer.closeAll();
        return false;
    });
    $("#addBtn").on('click',function () {
        if (taskArray.length == 0) {
            layer.msg('请先预览', {icon: 5});
            return;
        }
        var fields = JSON.stringify(taskArray);
        layer.confirm('确定要保存么?',function(){
            $.ajax({
                url: baseUrl+"/insTask/insertBatch",
                type: "post",
                contentType: "application/json;charset=utf-8",
                dataType: 'json',
                data: fields,
                success: function (data) {
                    if(data.code === 200 ){
                        layer.msg('保存成功', {icon: 1});
                        setTimeout(function () {
                            location.reload();
                        },1000);
                    }else{
                        layer.msg('保存失败', {icon: 5});
                    }
                }
            });

        });
    });

    function deleteRecord(id) {
        layer.confirm('确定要删除该任务么?',function(){
            var param = {"id":id};
            $.get(baseUrl+"/insTask/deleteTask",param, function(data) {
                if (data.code === 200) {
                    layer.msg('删除成功', {icon: 1});
                    setTimeout(function () {
                        active['reload'].call(this);
                    }, 1000);
                }else {
                    layer.msg('删除失败，请稍后重试!');
                }
            });
        });
    }
    function initFormParams(data) {
        $("#taskId").val(data.ID);
        var select1 = 'dd[lay-value=' + data.LINE_ID + ']';
        $('#lineName2').siblings("div.layui-form-select").find('dl').find(select1).click();
        $('#lineName2 option[value=' +data.LINE_ID+ ']').attr("selected", true);
        form.render('select', "lineName2");
        var select = 'dd[lay-value=' + data.STAFF_ID + ']';
        // 触发点击事件，实现自动选择
        $('#mulStaff2').siblings("div.layui-form-select").find('dl').find(select).click();
        $('#mulStaff2 option[value=' +data.STAFF_ID+ ']').attr("selected", true);
        form.render('select', "mulStaff2");
        laydate.render({
            elem: '#inspectDate2',
            type: 'date',
            min: nowTime,
            value:formatTime2(data.INSPECT_DATE)
        });
        laydate.render({
            elem: '#inspectStartTime2',
            type: 'time',
            value: data.INSPECT_START_TIME
        });
        $("#inspecTime").val(data.LINE_INSPECT_TIME);
        $("#inspecErrTime").val(data.LINE_INSPECT_ERROR_TIME);
        $("#taskStatus").empty().append(auditState(data.STATUS));
        // 未开始任务的任务才能编辑
        if(data.STATUS !== 0){
            $('#lineName2').attr("disabled","disabled");
            $('#mulStaff2').attr("disabled","disabled");
            $('#inspectDate2').attr("disabled","disabled");
            $('#inspectStartTime2').attr("disabled","disabled");
            $("#editBtn").hide();
        }else {
            $('#lineName2').removeAttr("disabled");
            $('#mulStaff2').removeAttr("disabled");
            $('#inspectDate2').removeAttr("disabled");
            $('#inspectStartTime2').removeAttr("disabled");
            $("#editBtn").show();
        }
        form.render();
    }
    // 查看任务中的 返回
    $("#backBtn").on('click',function () {
        layer.closeAll();
        return false;
    });
    // 线路选择
    form.on('select(lineName2)', function(data){
        $.get(baseUrl+"/insTask/getLineInfo",{"id":data.value}, function(result) {
            if (result.code === 200 && result.data != null) {
                $("#inspecTime").val(result.data.lineInspectTime);
                $("#inspecErrTime").val(result.data.lineInspectErrorTime);
            }
        });
        renderTasks($("#taskId").val(), data.value);
    });
    // 查看任务中的保存
    $("#editBtn").on('click',function () {
        var id = $("#taskId").val();
        var lineId = $("#lineName2").val();
        var staffId = $("#mulStaff2").val();
        var staff = $("#mulStaff2 option:selected").text().trim();
        var inspectDate = $("#inspectDate2").val();
        var inspectStartTime = $("#inspectStartTime2").val();
        var insTime = $("#inspecTime").val();
        var insErrTime = $("#inspecErrTime").val();
        var earlyTime = addHours(new Date(inspectDate+' '+inspectStartTime), parseInt((Number(insTime)-Number(insErrTime))));
        var lateTime = addHours(new Date(inspectDate+' '+inspectStartTime), parseInt((Number(insTime)+Number(insErrTime))));
        var fields = {"id":id, "lineId":lineId, "staffId":staffId, "staff":staff,"earliestFinishTime":earlyTime,
            "latestFinishTime": lateTime, "inspectDate":inspectDate, "inspectStartTime":inspectStartTime};
        layer.confirm('确定要修改么?',function(){
            $.ajax({
                url: baseUrl+"/insTask/updateTask",
                type: "post",
                data: fields,
                success: function (data) {
                    if(data.code === 200 ){
                        layer.msg('保存成功', {icon: 1});
                        setTimeout(function () {
                            location.reload();
                        },1000);
                    }else{
                        layer.msg('保存失败', {icon: 5});
                    }
                }
            });

        });
    });
    function renderTasks(id, lineId) {
        table.render({
            elem: '#pointList',
            url:  baseUrl+"/insTask/listPointItems?taskId="+id + "&lineId=" + lineId,
            method: 'get',
            cols: [[
                {type:'numbers',title: '序号'},
                {field: 'RECORD_ID', title: '巡检记录id',hide:true},
                {field: 'POINT_NAME', title: '点位名称',align:'center'},
                {field: 'POINT_DETAIL', title: '点位描述',align:'center'},
                {field: 'POINT_SYSTEM_INFO', title: '二维码信息',align:'center', templet:function(d){
                    var twoImg = drawImg(d.POINT_SYSTEM_INFO,options);
                    return '<img style="cursor: pointer" onclick="magnifyPic(this)" width="30" height="30" src="'+twoImg+'">';
                }},
                {field: 'RECORD_INSPECT_TIME', title: '巡检时间',align:'center',templet:function(d){
                        return formatTime(d.RECORD_INSPECT_TIME);
                    }},
                {field: 'RECORD_POINT_STATUS', title: '巡检结果',align:'center',templet:function(d){
                        return auditResult(d.RECORD_POINT_STATUS);
                    }}
            ]],
        });
    }
    function showRecordsDetail(data) {
        initFormParams(data);
        renderTasks(data.ID, data.LINE_ID);
        layer.open({
            type: 1,
            title:"查看任务",
            offset: 'auto',
            skin:'demo-class',
            closeBtn: 1,
            shift: 2,
            area: ['100%', '100%'],
            shadeClose: true,
            content: $("#check_task_main")
        });
    }
    function loadLineList(){
        $.get(baseUrl+'/insPointRecord/getLineList', {}, function (result) {
            if(result != null){
                if(result.data != null){
                    a$opt_html += "<option  value=''>全部</option>";
                    var $opt_html = "";
                    $.each(result.data, function (index, item) {
                        a$opt_html += "<option value='" + item.lineId + "'>" + item.lineName + "</option>";
                        $opt_html += "<option value='" + item.lineId + "'>" + item.lineName + "</option>";
                        var obj = {"key":item.lineId, "name":item.lineName,
                            "inspectTime":item.lineInspectTime,"inspectErrorTime":item.lineInspectErrorTime};
                        if(!hasDictKey(item.lineId)){
                            dictTypeArray.push(obj);
                        }
                        $("#line_name").empty().append(a$opt_html);
                        $("#lineName").empty().append($opt_html);
                        $("#lineName2").empty().append($opt_html);
                        form.render('select');
                    });

                }
            }
        });
    }
});
var a$opt_html;
var dictTypeArray = [];

function hasDictKey(key) {
    for(var i in dictTypeArray){
        if(dictTypeArray[i].key === key){
            return true;
        }
    }
    return false;
}
function reload(){
    $("#staff").val("");
    $("#startDate").val("");
    location.reload();
}
function auditState(status){
    var state = Number(status);
    switch (state){
        case 0: return '未开始';
        case 1: return '进行中';
        case 2: return '提早完成';
        case 3: return '按时完成';
        case 4: return '超时完成';
        case 5: return '已取消';
        case 6: return '已过期';
        default: return "--";
    }
}
function auditResult(status){
    switch (status){
        case 0: return '正常';
        case '0': return '正常';
        case 1: return '异常';
        case '1': return '异常';
        default: return "--";
    }
}
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
function magnifyPic(ele) {
    var bigH = 500;
    var bigW = 500;
    // 放大预览图片
    layer.open({
        type: 1,
        title: false,
        closeBtn: 1,
        shadeClose: true,
        area: ['550px', '550px'], //宽高
        content: "<img id='printImg' width='"+bigW+"' height='"+bigH+"' src=" + $(ele).attr("src") + " />"});
}